import { modal } from '@/widgets'
import { default as ListSelectVue } from './ListSelect.vue'

export function listSelect<T>(opts: {
  title: string
  icon?: string
  data: T[]
  getItemName: (t: T) => string
  getItemIcon?: (t: T) => string | null
  callback: (t: T) => void
}) {
  const { data, title, icon, getItemName: getName, getItemIcon: getIcon, callback } = opts
  const fn = getIcon || (() => null)
  const items = data.map((e, idx) => {
    return {
      idx,
      name: getName(e),
      icon: fn(e)
    }
  })
  const dialog = modal.create({
    component: ListSelectVue,
    props: { items, title, icon },
    events: {
      selected(idx: number) {
        dialog.destroy()
        if (idx >= 0) {
          const e = data[idx]
          callback(e)
        }
      }
    }
  })
}
